package top.igotcha.chapter.chapter7;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Gotcha
 * @date 2021/3/12
 * @describe
 */
@Slf4j(topic = "SingleThread")
public class SingleThreadTest {
    public static void main(String[] args) {
        // 自定义线程工厂
        ThreadFactory factory = new ThreadFactory() {
            AtomicInteger atomicInteger = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "gotchaThread_" + atomicInteger.getAndIncrement());
            }
        };

        ExecutorService pool = Executors.newSingleThreadExecutor(factory);
        pool.execute(()->log.debug("1"));
        pool.execute(()->{
            //当此任务出现异常时，之后的任务也会正常执行
            int i = 2/0;
            log.debug("2");
        });
        pool.execute(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("3");
        });
    }
}
